package com.chookss.video.recommend;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.adapter.DocunmentListAdapter;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.liulishuo.okdownload.DownloadTask;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class VideoDetailDirectoryFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    ConsecutiveScrollerLayout llBg;

    private DocunmentListAdapter adapter;
    private List<DocunmentEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private String courseCode;

    public VideoDetailDirectoryFragment(String courseCode) {
        this.courseCode = courseCode;
    }

    public VideoDetailDirectoryFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.common_recyclerview_top, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        llBg.setBackgroundColor(Color.parseColor("#ffffff"));
        rv.setPadding(Utils.dip2px(mContext, 2), 0, Utils.dip2px(mContext, 2), 0);
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new DocunmentListAdapter(R.layout.item_database_list, getActivity(), list, 0, 1, null, "VideoDetailDirectoryFragment_DownloadFile");

        rv.setAdapter(adapter);
        getData();
        registerBoradcastReceiver();
    }

    private RefreshLayout refreshLayout;

    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("courseCode", courseCode);
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.selectCourseConnectDatabase, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {

                JSONObject jsonObject = JSONObject.parseObject(data);
                if ("200".equals(jsonObject.getString("code"))) {
                    loadEnd();
                    if (rv == null || llNone == null) {
                        return;
                    }
                    String total = jsonObject.getString("total");
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    List<DocunmentEntity> DocunmentEntitys = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject userJson = jsonArray.getJSONObject(i);
                        DocunmentEntity docunmentEntity = JSON.toJavaObject(userJson, DocunmentEntity.class);
                        DocunmentEntitys.add(docunmentEntity);
                    }
                    if (currentPage == 1) {
                        list.clear();
                        adapter.notifyDataSetChanged();
                    }
                    HashMap<String, String> map = new HashMap<>();
                    map.put("directoryNum", total);
                    EventBus.getDefault().post(new MyEvent(map));
                    if (DocunmentEntitys != null && DocunmentEntitys.size() > 0) {
                        if (DocunmentEntitys.size() < pageSize) {
                            isEnd = true;
                        }
                        list.addAll(DocunmentEntitys);
                        adapter.notifyDataSetChanged();
                        rv.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    } else {
                        isEnd = true;
                        if (list.size() == 0) {
                            rv.setVisibility(View.GONE);
                            llNone.setVisibility(View.VISIBLE);
                        }
                    }
                    loadEnd();

                } else {
                    loadEnd();
                }

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
//        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<DocunmentEntity>>>() {
//        }.getType(), null, Urls.selectCourseConnectDatabase, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<DocunmentEntity>>() {
//            @Override
//            public void onSuccess(List<DocunmentEntity> data) {
//                if (currentPage == 1) {
//                    list.clear();
//                }
//                if (data != null && data.size() > 0) {
//                    if (data.size() < pageSize) {
//                        isEnd = true;
//                    }
//                    list.addAll(data);
//                    adapter.notifyDataSetChanged();
//                    rv.setVisibility(View.VISIBLE);
//                    llNone.setVisibility(View.GONE);
//                    HashMap<String,String> map=new HashMap<>();
//                    map.put("directoryNum",list.size()+"");
//                    EventBus.getDefault().post(new MyEvent(map));
//                } else {
//                    isEnd = true;
//                    if (list.size() == 0) {
//                        rv.setVisibility(View.GONE);
//                        llNone.setVisibility(View.VISIBLE);
//                    }
//                }
//                loadEnd();
//            }
//
//            @Override
//            public void onError(String errorMsg) {
//                loadEnd();
//                MyToast.show(Utils.onErrorTips(errorMsg));
//            }
//        });
    }

    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("dataCode")) {
                String recevierDataCode = map.get("dataCode");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(recevierDataCode)) {
                        int num = Utils.changeNumber(list.get(i).getReadNum());
                        list.get(i).setReadNum((num + 1) + "");
                        adapter.notifyItemChanged(i);
                    }
                }
            }
        }else  if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(map.get("DocumentPreview_error"))) {
                        list.get(i).setError(true);
                    }
                }

            }
        }
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!list.get(i).isOpen()) {
                            if(encryptStatus){
                                list.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }

                    }
                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);

            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    list.get(position).setProgress(percent);
                    adapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    list.get(position).setProgress(100);
                    adapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, "VideoDetailDirectoryFragment_DownloadFile");
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("VideoDetailDirectoryFragment_DownloadFile");// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && mContext != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

}
